import { history } from "@umijs/max";
import type { API } from "@/types/api"
// 删除原来的config导入
import "@ant-design/v5-patch-for-react-19";
import { Button, Tooltip, message } from "antd";
import { errorConfig } from "./requestErrorConfig";
import defaultSettings from "../config/defaultSettings";
import type { RequestConfig, RunTimeLayoutConfig } from "@umijs/max";
import { currentUser as queryCurrentUser } from "./services/core/api";
import { LogoutOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import type { Settings as LayoutSettings } from "@ant-design/pro-components";

const loginPath = "/login";

// 添加一个异步函数来获取配置
// let configPromise: Promise<any> | null = null;
// let resolvedConfig: any = null;

// function getConfig() {
//   if (!configPromise) {
//     configPromise = fetch('/config.json')
//       .then(response => response.json())
//       .catch(() => {
//         // 如果获取config.json失败，则使用默认值
//         console.warn('Failed to load config.json, using default config');
//         return { apiBaseUrl: "http://localhost:10585" }; // 默认值，与配置文件中一致
//       })
//       .then(config => {
//         resolvedConfig = config;
//         return config;
//       });
//   }
//   return configPromise;
// }

/**
 * @see https://umijs.org/docs/api/runtime-config#getinitialstate
 * */
export async function getInitialState(): Promise<{
    settings?: Partial<LayoutSettings>;
    currentUser?: API.CurrentUserResult;
    loading?: boolean;
    fetchUserInfo?: any;
}> {
    // @ts-ignore
    const fetchUserInfo = async (): Promise<API.CurrentUserResult> => {
        try {
            const user_id = localStorage.getItem("USER_UID");
            if (user_id === null) {
                history.push(loginPath);
            } else {
                return await queryCurrentUser({
                    uid: user_id,
                });
            }
        } catch (error: any) {
            message.error("用户信息获取失败！");
            history.push(loginPath);
            return error.response.data;
        }
    };

    const { location } = history;
    if (loginPath !== location.pathname) {
        const currentUser = await fetchUserInfo();
        return {
            fetchUserInfo,
            currentUser,
            settings: defaultSettings as Partial<LayoutSettings>,
        };
    }
    return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
    };
}

export const layout: RunTimeLayoutConfig = ({
    initialState,
    setInitialState,
}) => {
    return {
        avatarProps: {
            title: "用户",
            render: () => {
                return (
                    <>
                        <Tooltip title={"项目地址"}>
                            <Button
                                icon={<QuestionCircleOutlined />}
                                type={"text"}
                                onClick={() => {
                                    history.push(
                                        "https://gitee.com/fisherman_team/master",
                                    );
                                }}
                                size={"large"}
                            />
                        </Tooltip>
                        <Tooltip title={"退出"}>
                            <Button
                                icon={<LogoutOutlined />}
                                onClick={() => {
                                    history.push(loginPath);
                                    localStorage.clear();
                                }}
                                type={"text"}
                                size={"large"}
                            ></Button>
                        </Tooltip>
                    </>
                );
            },
        },
        onPageChange: () => {
            const { location } = history;
            if (!initialState?.currentUser && location.pathname !== loginPath) {
                history.push(loginPath);
            }
        },
        ...initialState?.settings,
    };
};

export const request: RequestConfig = {
    baseURL: undefined,
    // baseURL: API_BASE_URL,
    ...errorConfig,
};


export function onRouteChange() {
    if (history.location.pathname === "/") {
        history.replace("/hosting");
    }
}